# 作者：位微
# 你不是在写代码而是在解决问题
# 2025年09月09日22时02分46秒
# 2062873410@qq.com
import select
import socket
import sys

class ChatServer:
    def __init__(self,ip,port):
        self.ip=ip
        self.port=port
        self.sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        self.sock.bind((self.ip,self.port))
        self.sock.listen(5)
        # self.sock.setblocking(False)#设置为非阻塞
        self.epoll=select.epoll()

    def chat(self):
        # conn,addr=self.sock.accept()
        # print(addr,"连接成功")
        # self.epoll.register(conn.fileno(),select.EPOLLIN)
        self.epoll.register(self.sock.fileno(),select.EPOLLIN)
        self.epoll.register(sys.stdin.fileno(),select.EPOLLIN)
        while True:
            events=self.epoll.poll(-1)
            for fd,event in events:
                if fd==self.sock.fileno():
                    conn,addr=self.sock.accept()
                    print(addr,"连接成功")
                    self.epoll.register(conn.fileno(),select.EPOLLIN)
                elif fd==conn.fileno():
                    data=conn.recv(1024).decode('utf-8')
                    # 当接收到空数据时，说明对方断开连接
                    if not data:
                        print(addr,"断开连接")
                        self.epoll.unregister(fd)
                        conn.close()
                        break
                    print(data)
                elif fd==sys.stdin.fileno():
                    data=input()
                    conn.send(data.encode('utf-8'))
                # self.sock.close()
ChatServer("127.0.0.1",8080).chat()